<?php
namespace app\lib;
use yii\helpers\Json;

/**
 * 记录返回信息的，可以用于中间层返回信息，也可以用于类库信息返回
 */
class DataMessage {
    const STATE_SUCCESS = 0;
    const STATE_CLIENT_ERROR = 400;
    const STATE_SERVER_ERROR = 500;

    public $state;
    public $message;
    public $data;

    /**
     * @param int $state 完成状态
     * @param string $message 提示语
     * @param array|mixed $data 获取的数据，用于操作并返回数据的情况
     */
    function __construct($state, $message, $data = null) {
        $this->state = $state ?: self::STATE_SUCCESS;
        $this->message = !empty($message) ? $message : null;
        $this->data = $data;
    }

    // 增加一个$message到原本的内容里，参数可以是一个数组或者一个字符串
    public function addTitle($message) {
        $this->message = empty($this->message) ? $message : array_merge((array)$this->message, (array)$message);
    }

    public function getMessage() {
        return $this->message;
    }

    public function setMessage($message) {
        $this->message = $message;
    }

    // 获取设置查询state
    public function getState() {
        return $this->state;
    }

    public function setState($state) {
        $this->state = $state;
    }

    public function judgeState($state = self::STATE_SUCCESS) {
        return $this->state == $state;
    }

    public function getData() {
        return $this->data;
    }

    public function setData($data) {
        $this->data = $data;
    }

    public function addData($key, $value) {
        $this->data[$key] = $value;
    }

    public static function init($state = self::STATE_SUCCESS, $message = null, $data = null) {
        return new DataMessage($state, $message, $data);
    }

    public static function initSuccess($data = null) {
        return self::init(self::STATE_SUCCESS, '', $data);
    }

    public static function initFail($errorCode, $message = '', $data = null) {
        return self::init($errorCode, $message, $data);
    }

    public function __toString() {
        return Json::encode([
            'state' => $this->state ?: self::STATE_SUCCESS,
            'message' => $this->message ?: '',
            'data' => $this->data ?: array(),
        ]);
    }
}